<template>
  <div class="server-list-container">
    <div class="content-wrapper">
      <page-header
        title="自动化部署"
        description="本界面展示当前机房内所有未部署的服务器，可以通过BMC进行自动化部署操作。"
      >
        <el-input v-model="searchQuery" placeholder="搜索服务器..." class="search-input" clearable>
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </page-header>

      <!-- 服务器列表 -->
      <el-table
        v-loading="loading"
        :data="filteredServers"
        style="width: 100%"
        :height="tableHeight"
      >
        <el-table-column prop="id" label="ID" width="80" fixed="left" />
        <el-table-column prop="hostname" label="主机名" min-width="200" fixed="left">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              {{ row.hostname }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="server_brand" label="品牌" width="140" show-overflow-tooltip />
        <el-table-column prop="server_model" label="型号" width="140" show-overflow-tooltip />
        <el-table-column prop="location" label="起始位置" width="140">
          <template #default="{ row }"> {{ row.location }} U </template>
        </el-table-column>
        <el-table-column prop="height" label="高度" width="100">
          <template #default="{ row }"> {{ row.height }} U </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sn" label="序列号" width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click.stop="handleView(row)">查看</el-button>
            <el-button type="success" link @click.stop="handleDeploy(row)">部署</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          :teleported="false"
          popper-class="pagination-select-dropdown"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 部署确认对话框 -->
      <el-dialog
        v-model="deployDialogVisible"
        :title="deployStep === 1 ? '确认部署配置' : '确认重启服务器'"
        :width="480"
        :close-on-click-modal="false"
        align-center
        class="deploy-dialog"
      >
        <div class="deploy-confirm" v-loading="bmcLoading">
          <p v-if="deployStep === 1">确认修改以下服务器的启动项为PXE？</p>
          <p v-else>确认重启服务器开始自动部署？</p>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="主机名">
              {{ selectedServer?.hostname }}
            </el-descriptions-item>
            <el-descriptions-item label="序列号">
              {{ selectedServer?.sn }}
            </el-descriptions-item>
            <el-descriptions-item label="位置">
              {{ selectedServer?.location }} U
            </el-descriptions-item>
            <el-descriptions-item label="BMC信息">
              <template v-if="bmcInfo">
                <div class="bmc-info">
                  <div class="bmc-item">
                    <span class="label">IP地址:</span>
                    <span class="value">{{ bmcInfo.ip_address }}</span>
                  </div>
                  <div class="bmc-item">
                    <span class="label">MAC地址:</span>
                    <span class="value">{{ bmcInfo.mac_address }}</span>
                  </div>
                  <div class="bmc-item">
                    <span class="label">用户名:</span>
                    <span class="value">{{ bmcInfo.username }}</span>
                  </div>
                  <div class="bmc-item">
                    <span class="label">固件版本:</span>
                    <span class="value">{{ bmcInfo.firmware_version }}</span>
                  </div>
                </div>
              </template>
              <template v-else>
                <el-alert title="未找到BMC信息" type="warning" :closable="false" show-icon />
              </template>
            </el-descriptions-item>
          </el-descriptions>
          <div class="deploy-steps">
            <el-steps :active="deployStep" finish-status="success">
              <el-step title="修改配置" description="设置PXE启动" />
              <el-step title="重启服务器" description="开始自动部署" />
            </el-steps>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deployDialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              :loading="deployLoading"
              :disabled="countdown > 0"
              @click="confirmDeploy"
              class="confirm-btn"
            >
              {{
                countdown > 0
                  ? `确认${deployStep === 1 ? '修改' : '重启'} (${countdown}s)`
                  : `确认${deployStep === 1 ? '修改' : '重启'}`
              }}
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ServerInfo, BMCInfo } from '@/api/types'
import { assetService } from '@/api/assetService'
import { useRoomConfigStore } from '@/store/roomConfigStore'
import PageHeader from '@/components/common/PageHeader.vue'

const router = useRouter()
const roomConfigStore = useRoomConfigStore()
const loading = ref(false)
const deployLoading = ref(false)
const bmcLoading = ref(false)
const servers = ref<ServerInfo[]>([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const deployStep = ref(1)
const deployDialogVisible = ref(false)
const selectedServer = ref<ServerInfo | null>(null)
const bmcInfo = ref<BMCInfo | null>(null)
const countdown = ref(0)
let countdownTimer: NodeJS.Timer | null = null
const tableHeight = ref(500)

// 过滤后的服务器列表
const filteredServers = computed(() => {
  // 只显示未部署的服务器
  const undeployedServers = servers.value.filter((server) => server.status === 'undeployed')
  if (!searchQuery.value) return undeployedServers
  const query = searchQuery.value.toLowerCase()
  return undeployedServers.filter(
    (server) =>
      server.hostname.toLowerCase().includes(query) || server.sn.toLowerCase().includes(query),
  )
})

// 获取服务器列表
const fetchServers = async () => {
  loading.value = true
  try {
    if (!roomConfigStore.currentRoom) {
      ElMessage.warning('请先选择机房')
      return
    }
    const response = await assetService.getServersByRoom(roomConfigStore.currentRoom.room_id, {
      page: currentPage.value,
      pageSize: pageSize.value,
    })
    if (Array.isArray(response)) {
      servers.value = response
      total.value = response.length
    } else if (response.items && Array.isArray(response.items)) {
      servers.value = response.items
      total.value = response.total || response.items.length
    }
  } catch (err) {
    console.error('获取服务器列表失败:', err)
    ElMessage.error('获取服务器列表失败')
  } finally {
    loading.value = false
  }
}

// 监听机房变化
watch(
  () => roomConfigStore.currentRoom?.room_id,
  (newRoomId) => {
    if (newRoomId) {
      currentPage.value = 1 // 重置页码
      fetchServers()
    } else {
      servers.value = []
      total.value = 0
    }
  },
  { immediate: true },
)

// 处理分页
const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchServers()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchServers()
}

// 处理查看详情
const handleView = (server: ServerInfo) => {
  router.push(`/asset/server/${server.id}`)
}

// 处理部署
const handleDeploy = async (server: ServerInfo) => {
  selectedServer.value = server
  deployStep.value = 1
  deployDialogVisible.value = true
  countdown.value = 10
  startCountdown()

  // 获取BMC信息
  bmcLoading.value = true
  try {
    bmcInfo.value = await assetService.getBMCInfo(server.id)
  } catch (err) {
    console.error('获取BMC信息失败:', err)
    bmcInfo.value = null
  } finally {
    bmcLoading.value = false
  }
}

// 确认部署
const confirmDeploy = async () => {
  if (!selectedServer.value) return

  deployLoading.value = true
  try {
    if (deployStep.value === 1) {
      // 第一步：修改配置
      await assetService.resetServerConfig(selectedServer.value.id)
      ElMessage.success('配置修改成功')
      deployStep.value = 2
      countdown.value = 10
      startCountdown()
    } else {
      // 第二步：重启服务器
      await assetService.rebootServer(selectedServer.value.id)
      ElMessage.success('重启命令已发送，服务器开始自动部署')
      deployDialogVisible.value = false
      // 重新加载服务器列表
      fetchServers()
    }
  } catch (err) {
    console.error('操作失败:', err)
    ElMessage.error(deployStep.value === 1 ? '配置修改失败' : '重启命令发送失败')
  } finally {
    deployLoading.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  // 清除可能存在的旧定时器
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }

  countdownTimer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(countdownTimer!)
      countdownTimer = null
    }
  }, 1000)
}

// 监听对话框关闭
watch(deployDialogVisible, (newVal) => {
  if (!newVal) {
    // 对话框关闭时重置状态
    if (countdownTimer) {
      clearInterval(countdownTimer)
      countdownTimer = null
    }
    countdown.value = 0
    deployStep.value = 1
  }
})

// 组件卸载时清理
onBeforeUnmount(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
})

// 计算表格高度
const updateTableHeight = () => {
  const vh = window.innerHeight
  tableHeight.value = vh - 64 - 48 - 52 - 32 - 24
}

// 监听窗口大小变化
onMounted(() => {
  updateTableHeight()
  window.addEventListener('resize', updateTableHeight)
  fetchServers()
})

onUnmounted(() => {
  window.removeEventListener('resize', updateTableHeight)
})

// 获取状态类型
const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    online: 'success',
    offline: 'danger',
    undeployed: 'info', // 添加未部署状态的样式
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    online: '在线',
    offline: '离线',
    undeployed: '未部署', // 添加未部署状态的文本
  }
  return textMap[status] || status
}
</script>

<style scoped lang="scss">
.server-list-container {
  height: 100%;

  .content-wrapper {
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;
    padding-bottom: 48px;

    :deep(.el-table) {
      border: none;
      margin-bottom: 0;

      .el-table__body-wrapper {
        overflow-y: auto;
      }

      // 固定列阴影
      .el-table__fixed-right::before,
      .el-table__fixed::before {
        display: none;
      }

      // 表头样式
      .el-table__header {
        th {
          background-color: var(--el-fill-color-darker);
          &.is-leaf {
            border-bottom: 1px solid var(--el-border-color-lighter);
          }
          .cell {
            font-weight: 600;
            color: var(--el-text-color-regular);
            font-size: 14px;
          }
        }
      }

      &::after {
        display: none;
      }

      .el-table__cell {
        border-bottom: 1px solid var(--el-border-color-lighter);
      }

      // 优化行样式
      .el-table__row {
        &:hover {
          background-color: var(--el-fill-color-light);
        }

        .el-table__cell {
          border-bottom: 1px solid var(--el-border-color-lighter);
        }
      }

      .el-button--link {
        height: auto;
        padding: 4px 8px;
        font-size: 14px;
        font-weight: normal;
      }
    }

    .pagination {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 32px;
      display: flex;
      justify-content: flex-end;
      padding: 8px 8px 8px 0;
      border-top: 1px solid var(--el-border-color-lighter);
      z-index: 1;

      :deep(.el-pagination) {
        white-space: nowrap;
        .el-select .el-input {
          margin: 0;
        }

        .el-select__popper {
          margin-top: -4px;
        }

        .el-select-dropdown {
          margin-top: 0 !important;
        }
      }
    }
  }
}
/* 新增全局样式（注意需要穿透scoped限制） */
:deep(.pagination-select-dropdown) {
  /* 强制弹窗向上展开 */
  top: auto !important;
  bottom: 100%;
  margin-bottom: 28px; /* 添加与分页器的间距 */

  /* 调整箭头方向 */
  .el-popper__arrow {
    top: 100%;
    bottom: auto;
    transform: translateY(-50%) rotate(180deg);
  }
}

.deploy-confirm {
  p {
    margin-bottom: 16px;
    color: var(--el-text-color-regular);
    font-size: 14px;
  }

  .bmc-info {
    display: flex;
    flex-direction: column;
    gap: 6px;

    .bmc-item {
      display: flex;
      align-items: center;

      .label {
        width: 60px;
        color: var(--el-text-color-secondary);
        font-size: 13px;
      }

      .value {
        color: var(--el-text-color-primary);
        font-family: var(--el-font-family-monospace);
        font-size: 13px;
        flex: 1;
        min-width: 0;
        word-break: break-all;
      }
    }
  }

  .deploy-steps {
    margin-top: 20px;
    padding: 0 20px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin: 0;
  padding: 0;

  .el-button {
    min-width: 80px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    height: 30px;
    padding: 0 12px;

    &:disabled {
      cursor: not-allowed;
      background-color: var(--el-button-disabled-bg-color);
      border-color: var(--el-button-disabled-border-color);
      color: var(--el-button-disabled-text-color);
    }

    &.confirm-btn {
      letter-spacing: 1px;
    }
  }
}

/* 对话框样式 */
.deploy-dialog {
  :deep(.el-dialog) {
    margin-top: 15vh !important;
  }

  :deep(.el-dialog__body) {
    padding: 12px;
  }

  :deep(.el-descriptions__cell) {
    padding: 6px 8px;

    &.el-descriptions__label {
      width: 60px;
      color: var(--el-text-color-regular);
    }
  }

  :deep(.el-dialog__footer) {
    padding: 10px 12px;
    border-top: 1px solid var(--el-border-color-lighter);
  }
}
</style>
